import { Base64 } from "js-base64";
import CryptoJS from 'crypto-js';
import JSEncrypt from "jsencrypt";

//生成aes密钥
export function generateKey() {
  // 生成一个随机的AES密钥，长度为16, 24或32字节（对应AES-128, AES-192, AES-256）
  // 这里我们生成一个AES-256位的密钥（32字节）
  let aesKey = CryptoJS.lib.WordArray.random(8).toString(CryptoJS.enc.Hex);
  console.log('Generated AES Key:', Base64.encode(aesKey));
  return Base64.encode(aesKey)
}
//aes加密
export function aesEncrypt(data, keyStr) {
  keyStr = keyStr ? keyStr : "absoietlj32fai12";
  let key = CryptoJS.enc.Utf8.parse(Base64.decode(keyStr));
  let srcs = CryptoJS.enc.Utf8.parse(data);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
}
//aes解密
export function aesDecrypt(data, keyStr) {
  keyStr = keyStr ? keyStr : 'abcdsxyzhkj12345';
  var key = CryptoJS.enc.Utf8.parse(Base64.decode(keyStr));
  var decrypt = CryptoJS.AES.decrypt(data, key,
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
//rsa加密
export function encodeAesKey(data, rasKey) {
  let temp = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsYDO+PiTwoa1FHkCtdUtqMDvyTSMGtYJBja+LnYKB+bmymINtmhim8Dr2CH1v8UyRyRJCSoFpCgmNH74fYFKOemThCIsBwtJw8ca06yUsBNmM20vPYQfW/tCLkTY0pkYsSLr4cIe3XSnVnlk/ZiiTCt/F6y4H7bii8YhKk7FW3cTWRS/JlSRD7OnFirZcP8uGWfe1hDT9gQZWURtLj5P0f9wWlkRqf7bIqk9rsMIH62Y3yme4HHsY4uMdR3kSTkqL5su+xhbwsGHdgzjxKKhYhVq27w/gmfglCWR3FCqwqvCLKIf4nplW09vMvKt/L4KhScGi+tena1YHcHO6x31uwIDAQAB"
  let encrypt = new JSEncrypt();
  encrypt.setPublicKey(temp);
  let aaaa = encrypt.encrypt(data)
  return aaaa
}

